import { Component } from "react";

import {List, InputItem, Picker, ImagePicker, TextareaItem, Toast} from "antd-mobile";
import NavHeader from "../../../components/NavHeader";
import HousePackage from "../../HousePackage";

import styles from './index.module.css'
import { API } from "../../../utils/api";
import { BASE_URL } from "../../../utils/url";

// supporting图标
const HOUSE_PACKAGE = [
  {
    id: 1,
    name: '衣柜',
    icon: 'icon-wardrobe'
  },
  {
    id: 2,
    name: '洗衣机',
    icon: 'icon-wash'
  },
  {
    id: 3,
    name: '空调',
    icon: 'icon-air'
  },
  {
    id: 4,
    name: '天然气',
    icon: 'icon-gas'
  },
  {
    id: 5,
    name: '冰箱',
    icon: 'icon-ref'
  },
  {
    id: 6,
    name: '暖气',
    icon: 'icon-Heat'
  },
  {
    id: 7,
    name: '电视',
    icon: 'icon-vid'
  },
  {
    id: 8,
    name: '热水器',
    icon: 'icon-heater'
  },
  {
    id: 9,
    name: '宽带',
    icon: '',
    word: '&#xe90e;'
  },
  {
    id: 10,
    name: '沙发',
    icon: 'icon-sofa'
  },
]

// 房屋类型
const roomTypeData = [
  {label: '一室', value: 'ROOM|d4a692e4-a177-37fd'},
  {label: '二室', value: 'ROOM|d1a00384-5801-d5cd'},
  {label: '三室', value: 'ROOM|20903ae0-c7bc-f2e2'},
  {label: '四室', value: 'ROOM|ce2a5daa-811d-2f49'},
  {label: '四室+', value: 'ROOM|2731c38c-5b19-ff7f'},
]


// 朝向
const orientedData = [
  {label: '东', value: 'ORIEN|141b98bf-1ad0-11e3'},
  {label: '西', value: 'ORIEN|103fb3aa-e8b4-de0e'},
  {label: '南', value: 'ORIEN|61e99445-e95e-7f37'},
  {label: '北', value: 'ORIEN|caa6f80b-b764-c2df'},
  {label: '东南', value: 'ORIEN|dfb1b36b-e0d1-0977'},
  {label: '东北', value: 'ORIEN|67ac2205-7e0f-c057'},
  {label: '西南', value: 'ORIEN|2354e89e-3918-9cef'},
  {label: '西北', value: 'ORIEN|80795f1a-e32f-feb9'},
]

// 楼层
const floorData = [
  {label: '高楼层', value: 'FLOOR|1'},
  {label: '中楼层', value: 'FLOOR|2'},
  {label: '低楼层', value: 'FLOOR|3'},
]

const Item = List.Item

export default class RentAdd extends Component {
  constructor(props) {
    super(props)
    
    const { state } = props.location

    this.community = {}
    this.imgFiles = []
    this.roomType = ''
    this.price = ''
    this.oriented = ''
    this.floor = ''
    this.size = ''
    this.title = ''
    this.supporting = []
    this.description = ''
    this.selectedStatus = Array(HOUSE_PACKAGE.length).fill(false)

    // 有小区数据
    if (state) {
      this.community.name = state.name
      this.community.id = state.id
    }
    // 编辑页面跳转
    if (state && state.house) {
      // 设置community
      this.community.name = state.house.community
      // 设置imgFiles
      state.house.houseImg.map(url => {
        this.imgFiles.push({
          url: BASE_URL+url
        })
        return null
      })
      // 设置roomType
      this.roomType = roomTypeData.filter(item => item.label === state.house.roomType)[0].value
      // 设置floor
      this.floor = floorData.filter(item => item.label === state.house.floor)[0].value
      // 设置oriented
      this.oriented = orientedData.filter(item => item.label === state.house.oriented[0])[0].value  
      // 设置price
      this.price = state.house.price + ''
      // 设置size
      this.size = state.house.size + ''
      //设置title
      this.title = state.house.title
      // 设置description
      this.description = state.house.description
      // 设置supporting
      this.supporting = state.house.supporting
      // 设置selectedStatus
      HOUSE_PACKAGE.map((item, id) => {
        if (this.supporting.indexOf(item['name']) !== -1) {
          this.selectedStatus[id] = true
        } else {
          this.selectedStatus[id] = false
        }
        return null
      })
    }

    this.state = {
      // 小区信息
      community: this.community,
      // 房型
      roomType: this.roomType,
      // 图片存储
      imgFiles: [],
      // 上传房屋图片路径字符
      houseImg: '',
      // 图片是否可多选
      multiple: true,
      // 房屋配置图标选择状态
      selectedStatus: this.selectedStatus,
      // 房屋价格
      price: this.price,
      // 房屋朝向
      oriented: this.oriented,
      // 房屋楼层:
      floor: this.floor,
      // 建筑面积
      size: this.size,
      // 房屋标题
      title: this.title,
      // 房屋配套
      supporting: this.supporting,
      // 房屋描述
      description: this.description
    }
  }

  onChange = (val, type) => {
    this.setState({
      [type]: val
    })
  }

  saveImg = (files) => {
    this.setState({
      imgFiles: files,
    });
  }

  onSelect = (idx, name) => {
    let { selectedStatus, supporting } = this.state
    selectedStatus[idx] = !selectedStatus[idx]

    let pl = supporting.indexOf(name)
    if (pl !== -1) {
      supporting.splice(pl, 1)
    } else {
      supporting.push(name)
    }
    
    this.setState({
      selectedStatus,
      supporting
    })
  }
  
  addHouse = async () => {
    const { imgFiles, title, description, price, oriented, size, supporting, roomType, floor, community } = this.state
    let houseImg = ''

    // 上传房屋图片
    if (imgFiles.length) {
      // 存在上传图片
      const form = new FormData()
      imgFiles.forEach(item => form.append('file', item.file))
      let res = await API.post('/houses/image', form, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      })
      houseImg = res.data.body.join('|')
      this.setState({
        houseImg
      })
    }

    // 发布房源
    try {
      let res1 = await API.post('/user/houses', {
        title, description, price, oriented, size, supporting: supporting.join('|'), roomType, floor, community: community.id, houseImg
      })
      if (res1.data.status === 200) {
        // 发布成功
        Toast.info('发布成功', 0.5, null, false)
        this.props.history.replace('/rent')
      } else {
        Toast.info(res1.data.description, 0.5, null, false)
      }
    } catch(err) {
      Toast.info('请求错误', 0.5, null, false)
    }
  }

  handleClear = () => {
    // 清空state
    this.setState({
      community: {},
      roomType: '',
      imgFiles: [],
      houseImg: '',
      multiple: true,
      selectedStatus: Array(10).fill(false),
      price: '',
      size: '',
      oriented: '',
      floor: '',
      title: '',
      supporting: [],
      description: ''
    })
  }

  render() {
    const { community, imgFiles, multiple, selectedStatus, roomType, price, size, floor, oriented, title, description } = this.state
    const { name } = community

    return (
      <div className={styles.add}>
        <NavHeader>发布房源</NavHeader>
        {/* 房源信息 */}
        <List
          renderHeader={() => '房源信息'}
        >
          <Item
            arrow={"horizontal"}
            onClick={() => {this.props.history.replace('/rent/search')}}
            extra={name || "请输入小区名称"}
          >小区名称</Item>
          <InputItem
            placeholder="请输入租金/月"
            extra="￥/月"
            value={price}
            onChange={(val) => this.onChange(val, 'price')}
          >租&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;金</InputItem>
          <InputItem
            placeholder="请输入建筑面积"
            extra="㎡"
            value={size}
            onChange={(val) => this.onChange(val, 'size')}
          >建筑面积</InputItem>
          <Picker
            data={roomTypeData}
            cols={1}
            value={[roomType]}
            onOk={v => this.onChange(v[0], 'roomType')}
          >
            <List.Item arrow="horizontal" onClick={this.onClick}>户&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型</List.Item>
          </Picker>
          <Picker
            data={floorData}
            cols={1}
            value={[floor]}
            onOk={v => this.onChange(v[0], 'floor')}
          >
            <List.Item arrow="horizontal" onClick={this.onClick}>所在楼层</List.Item>
          </Picker>
          <Picker
            data={orientedData}
            cols={1}
            value={[oriented]}
            onOk={v => this.onChange(v[0], 'oriented')}
          >
            <List.Item arrow="horizontal" onClick={this.onClick}>朝&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;向</List.Item>
          </Picker>
        </List>

        {/* 房屋标题 */}
        <List
          renderHeader={() => '房屋标题'}
        >
          <InputItem
            placeholder="请输入标题（例如：整租 小区名 2室 5000元）"
            value={title}
            onChange={(val) => this.onChange(val, 'title')}
          ></InputItem>
        </List>

        {/* 房屋图像 */}
        <List
          renderHeader={() => '房屋图像'}
        >
          <ImagePicker
            files={imgFiles}
            onChange={this.saveImg}
            selectable={imgFiles.length < 7}
            multiple={multiple}
          />
        </List>

        {/* 房屋配置 */}
        <List
          renderHeader={() => '房屋配置'}
        >
          <HousePackage select={true} onSelect={this.onSelect} selectedStatus={selectedStatus}></HousePackage>
        </List>
        
        {/* 房屋描述 */}
        <List
          renderHeader={() => '房屋描述'}
        >
          <TextareaItem
            rows={2}
            count={200}
            placeholder="请输入房屋描述"
            autoHeight
            value={description}
            onChange={(val) => this.onChange(val, 'description')}
          />
        </List>

        {/* 底部按钮 */}
        <div className={styles.footer}>
          <div className={styles.left} onClick={this.handleClear}>清空</div>
          <div className={styles.right} onClick={this.addHouse}>提交</div>
        </div>
      </div>
    )
  }
}